import * as argon2 from 'argon2'
import { nanoid } from 'nanoid'
import { YdbDataType, YdbModel, YdbSchemaType } from 'ydb-orm'

type Fields = {
  id: string
  login: string
  password: Date
  createdAt: Date
}

export class User extends YdbModel implements Fields {
  static schema: YdbSchemaType = {
    id: YdbDataType.ascii,
    login: YdbDataType.ascii,
    password: YdbDataType.ascii,
    createdAt: YdbDataType.date,
  }

  // can be autogenerated after `implements` use
  id: Fields['id']
  login: Fields['login']
  password: Fields['password']
  createdAt: Fields['createdAt']

  constructor(fields: Fields) {
    super(fields)
    const {
      login, createdAt, id = null, password,
    } = fields
    this.id = id || nanoid()
    this.login = login
    this.password = password
    this.createdAt = createdAt || new Date()
  }

  async hash(password: string) {
    this.password = await argon2.hash(password)
  }

  async check(password: string) {
    if (await argon2.verify(this.password, password)) {
      return true
    }
    return false
  }
}
